package com.hm.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hm.config.AuthProperties;
import com.hm.util.JwtTool;
import com.hmall.common.utils.CollUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
         //1.获取请求头中的request
        ServerHttpRequest request = exchange.getRequest();
        //校验是否需要拦截
        if(isExclude(request.getPath().toString())){
            return chain.filter(exchange);
        }

        //2.获取token
        String token = null;
        List<String> authorization = request.getHeaders().get("authorization");
if(!CollUtils.isEmpty( authorization)){
      token = authorization.get(0);
}
        //3.校验token

        Long userId;
        try{
              userId = jwtTool.parseToken(token);//不希望返回 无效的token等这种书面语 换成未登录/失败 的状态码

        }catch(Exception e){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();//终止请求
        }
        //  4.传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange  swe = exchange.mutate().request(b -> b.header("UserInfo", userInfo)).build();
        //5.放行
        return chain.filter(swe);
    }

    private boolean isExclude(String string) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath,string)){//authProperties.getExcludePaths().contains(string)精准匹配
                return true;
            }
        }

        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
